import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:video_player/video_player.dart';

class MediaPreviewController extends GetxController {
  late final PageController _pageController;
  late final List<AssetEntity> _mediaList;
  late int _currentIndex;

  final _videoController = Rxn<VideoPlayerController>();
  final _isVideoPlaying = false.obs;

  List<AssetEntity> get mediaList => _mediaList;
  PageController get pageController => _pageController;
  VideoPlayerController? get videoController => _videoController.value;
  get isVideoPlaying => _isVideoPlaying.value;

  @override
  void onInit() {
    super.onInit();
    _mediaList = Get.arguments['mediaList'];
    _currentIndex = Get.arguments['index'];
    _pageController = PageController(initialPage: _currentIndex);
    _loadCurrentMedia();
  }

  void onPageChanged(int index) {
    _currentIndex = index;
    _loadCurrentMedia();
  }

  void playVideo() {
    _isVideoPlaying.value ? _videoController.value?.pause() : _videoController.value?.play();
    _isVideoPlaying.value = !_isVideoPlaying.value;
  }

  void _loadCurrentMedia() async {
    // 释放之前的视频控制器
    if (_videoController.value != null) {
      _videoController.value?.dispose();
      _videoController.value = null;
      _isVideoPlaying.value = false;
    }

    final asset = _mediaList[_currentIndex];

    if (asset.type == AssetType.video) {
      final file = await asset.file;
      if (file != null) {
        _videoController.value = VideoPlayerController.file(file);
        _videoController.value?.initialize();
      }
    }
  }

  @override
  void onClose() {
    _pageController.dispose();
    _videoController.value?.dispose();
    super.onClose();
  }
}
